﻿@model IList<ProductDetailsModel.ProductVariantModel.ProductVariantAttributeModel>
@using Nop.Web.Models.Catalog;
@using Nop.Core.Domain.Catalog;
@using Nop.Core.Infrastructure;
@using Nop.Core;
@using System.Text;
@using System.Globalization;
@using Nop.Web.Framework;
@using Nop.Services.Customers;
@using Nop.Services.Security;
@{
    var hidePrices = !EngineContext.Current.Resolve<IPermissionService>().Authorize(StandardPermissionProvider.DisplayPrices);

    var dynamicPriceUpdate = EngineContext.Current.Resolve<CatalogSettings>().EnableDynamicPriceUpdate;
    var adjustmentTableScripts = new StringBuilder();
    var attributeScripts = new StringBuilder();

    string adjustmentTableName = "";
    string adjustmentFuncName = "";
    string priceVarName = "";
    string priceVarClass = "";

    if (dynamicPriceUpdate && !hidePrices)
    {
        foreach (var attribute in Model)
        {
            string controlId = string.Format("product_attribute_{0}_{1}_{2}", attribute.ProductVariantId, attribute.ProductAttributeId, attribute.Id);

            adjustmentTableName = string.Format("adjustmentTable_{0}", attribute.ProductVariantId);
            adjustmentFuncName = string.Format("adjustPrice_{0}", attribute.ProductVariantId);
            priceVarName = string.Format("priceValForDynUpd_{0}", attribute.ProductVariantId);
            priceVarClass = string.Format("price-val-for-dyn-upd-{0}", attribute.ProductVariantId);

            switch (attribute.AttributeControlType)
            {
                case AttributeControlType.DropdownList:
                    {
                        adjustmentTableScripts.AppendFormat("{0}['{1}'] = new Array(", adjustmentTableName, controlId);
                        attributeScripts.AppendFormat("$('#{0}').change(function(){{{1}();}});\n", controlId, adjustmentFuncName);
                        int numberOfJsArrayItems = 0;
                        if (!attribute.IsRequired)
                        {
                            adjustmentTableScripts.AppendFormat(CultureInfo.InvariantCulture, "{0},", decimal.Zero);
                            numberOfJsArrayItems++;
                        }

                        foreach (var pvaValue in attribute.Values)
                        {
                            adjustmentTableScripts.AppendFormat(CultureInfo.InvariantCulture, "{0},", (float)pvaValue.PriceAdjustmentValue);
                            numberOfJsArrayItems++;
                        }

                        //If you create an array with a single numeric parameter, that number is used for specifying the number of elements in this array.
                        //so have a little hack here (we need at least two elements)
                        if (numberOfJsArrayItems == 1)
                        {
                            adjustmentTableScripts.AppendFormat(CultureInfo.InvariantCulture, "{0},", decimal.Zero);
                        }
                        adjustmentTableScripts.Length -= 1;
                        adjustmentTableScripts.Append(");\n");
                    }
                    break;
                case AttributeControlType.RadioList:
                    {
                        foreach (var pvaValue in attribute.Values)
                        {
                            adjustmentTableScripts.AppendFormat(CultureInfo.InvariantCulture, "{0}['{1}_{2}'] = {3};\n", adjustmentTableName, controlId, pvaValue.Id, (float)pvaValue.PriceAdjustmentValue);
                            attributeScripts.AppendFormat("$('#{0}_{1}').click(function(){{{2}();}});\n", controlId, pvaValue.Id, adjustmentFuncName);
                        }
                    }
                    break;
                case AttributeControlType.Checkboxes:
                    {
                        foreach (var pvaValue in attribute.Values)
                        {
                            adjustmentTableScripts.AppendFormat(CultureInfo.InvariantCulture, "{0}['{1}_{2}'] = {3};\n", adjustmentTableName, controlId, pvaValue.Id, (float)pvaValue.PriceAdjustmentValue);
                            attributeScripts.AppendFormat("$('#{0}_{1}').click(function(){{{2}();}});\n", controlId, pvaValue.Id, adjustmentFuncName);
                        }
                    }
                    break;
                default:
                    break;
            }

        }
    }
}
@if (Model.Count > 0)
{
    if (dynamicPriceUpdate && !hidePrices)
    {
    <script type="text/javascript">
    // Adjustment table
    var @(adjustmentTableName) = new Array();
    // Adjustment table initialize
    @Html.Raw(adjustmentTableScripts.ToString())
    // Adjustment function
    function @(adjustmentFuncName)() {
        var sum = 0;
        for(var i in @(adjustmentTableName)) {
            var ctrl = $('#' + i);
            if((ctrl.is(':radio') && ctrl.is(':checked')) || (ctrl.is(':checkbox') && ctrl.is(':checked'))) {
                sum += @(adjustmentTableName)[i];
            }
            else if(ctrl.is('select')) {
                var idx = $('#' + i + " option").index($('#' + i + " option:selected"));
                if(idx != -1) {
                    sum += @(adjustmentTableName)[i][idx];
                }
            }
        }
        var res = (@(priceVarName) + sum).toFixed(2);
        $(".@(priceVarClass)").text(res);
    }
    // Attributes handlers
    $(document).ready(function() {
        @(adjustmentFuncName)();
        @Html.Raw(attributeScripts.ToString())
    });
    </script>
    }
    <div class="attributes">
        @foreach (var attribute in Model)
        {
            string controlId = string.Format("product_attribute_{0}_{1}_{2}", attribute.ProductVariantId, attribute.ProductAttributeId, attribute.Id);
            <div>
                @if (attribute.IsRequired)
                {
                    <span>*</span>
                }
                @if (!string.IsNullOrEmpty(attribute.TextPrompt))
                {
                    <span class="textprompt">@attribute.TextPrompt</span>
                }
                else
                {
                    <span class="textprompt">@attribute.Name</span>
                }
                @if (!string.IsNullOrEmpty(attribute.Description))
                {
                    <br />
                    <span>@Html.Raw(attribute.Description)</span>
                }
                @if (attribute.AttributeControlType == AttributeControlType.TextBox ||
                    attribute.AttributeControlType == AttributeControlType.FileUpload)
                {
                    <text>&nbsp;&nbsp;&nbsp;</text>
                }
                else
                {
                    <br />
                }
                @switch (attribute.AttributeControlType)
                {
                    case AttributeControlType.DropdownList:
                        {
                    <select name="@(controlId)" id="@(controlId)">
                        @if (!attribute.IsRequired)
                        {
                            <option value="0">---</option>
                        }
                        @foreach (var pvaValue in attribute.Values)
                        {
                            <option @(pvaValue.IsPreSelected ? Html.Raw(" selected=\"selected\"") : null) value="@pvaValue.Id">@pvaValue.Name
                                @(!String.IsNullOrEmpty(pvaValue.PriceAdjustment) ? " [" + pvaValue.PriceAdjustment + "]" : null)
                            </option>
                        }
                    </select>
                        }
                        break;
                    case AttributeControlType.RadioList:
                        {
                            foreach (var pvaValue in attribute.Values)
                            {
                    <input id="@(controlId)_@(pvaValue.Id)" type="radio" name="@(controlId)" value="@pvaValue.Id" @(pvaValue.IsPreSelected ? Html.Raw(" checked=\"checked\"") : null) />
                    <label for="@(controlId)_@(pvaValue.Id)">@pvaValue.Name @(!String.IsNullOrEmpty(pvaValue.PriceAdjustment) ? " [" + pvaValue.PriceAdjustment + "]" : null)</label>
                            }
                        }
                        break;
                    case AttributeControlType.Checkboxes:
                        {
                            foreach (var pvaValue in attribute.Values)
                            {
                    <input id="@(controlId)_@(pvaValue.Id)" type="checkbox" name="@(controlId)" value="@pvaValue.Id" @(pvaValue.IsPreSelected ? Html.Raw(" checked=\"checked\"") : null) />
                    <label for="@(controlId)_@(pvaValue.Id)">@pvaValue.Name @(!String.IsNullOrEmpty(pvaValue.PriceAdjustment) ? " [" + pvaValue.PriceAdjustment + "]" : null)</label>
                            }
                        }
                        break;
                    case AttributeControlType.TextBox:
                        {
                    <input name="@(controlId)" type="text" class="textbox" id="@(controlId)" value="@attribute.TextValue" />
                        }
                        break;
                    case AttributeControlType.MultilineTextbox:
                        {
                    <textarea cols="20" id="@(controlId)" name="@(controlId)">@attribute.TextValue</textarea>
                        }
                        break;
                    case AttributeControlType.Datepicker:
                        {
                    @Html.DatePickerDropDowns(controlId + "_day", controlId + "_month", controlId + "_year", DateTime.Now.Year, DateTime.Now.Year + 1, attribute.SelectedDay, attribute.SelectedMonth, attribute.SelectedYear)
                        }
                        break;
                    case AttributeControlType.FileUpload:
                        {
                            //register CSS and JS
                            Html.AddCssFileParts(@Url.Content("~/Content/fileuploader/fileuploader.css"));
                            Html.AddScriptParts(@Url.Content("~/Scripts/fileuploader.js"));

                            //ex. ['jpg', 'jpeg', 'png', 'gif'] or []
                            var allowedFileExtensions = string.Join(", ", attribute.AllowedFileExtensions.Select(x => "'" + x.Trim() +"'").ToList());
                            
                            <input id="@(controlId)" name="@(controlId)" type="hidden" />
                            <div id="@(controlId)uploader">
                            </div>
                            <script type="text/javascript">
                            $(function () {                   
                                var @(controlId)uploader = new qq.FileUploader({
                                    element: document.getElementById('@(controlId)uploader'),
                                    action: '@(Url.RouteUrl("UploadFileProductAttribute", new { productVariantId = @attribute.ProductVariantId, productAttributeId = @attribute.ProductAttributeId }))',
                                    onComplete: function(id, fileName, responseJSON){
                                        $("#@(controlId)").val(responseJSON.downloadGuid);
                                        if (responseJSON.message) {
                                            alert(responseJSON.message);
                                        }
                                    },
                                    allowedExtensions: [@Html.Raw(allowedFileExtensions)],
                                    strings: {
                                        upload: "@T("Common.FileUploader.Upload")",
                                        drop: "@T("Common.FileUploader.DropFiles")",
                                        cancel: "@T("Common.FileUploader.Cancel")",
                                        failed: "@T("Common.FileUploader.Failed")"
                                    }
                                });
                            });
                            </script>
                        }
                        break;
                }
            </div>
        }
    </div>
}